import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.stream.Collectors;

public class OrderService {
    private List<Order> orders = new ArrayList<>();
    private Integer nextId = 1;

    public Order createOrder(Integer userId, List<OrderItem> items) {
        if (items == null || items.isEmpty()) {
            return null;
        }

        Double totalAmount = items.stream()
                .mapToDouble(OrderItem::getSubtotal)
                .sum();

        Order order = new Order(nextId++, userId, new ArrayList<>(items), totalAmount, new Date(), "PENDING");
        orders.add(order);
        return order;
    }

    public List<Order> getUserOrders(Integer userId) {
        return orders.stream()
                .filter(o -> o.getUserId().equals(userId))
                .collect(Collectors.toList());
    }

    public List<Order> getAllOrders() {
        return new ArrayList<>(orders);
    }
}